package com.ideal.frame.config;

import com.ideal.frame.convert.EnumConvertFactory;
import com.ideal.frame.interceptor.LogInterceptor;
import com.ideal.frame.interceptor.PermissionInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @Author: jin
 * @Description: webmvc配置
 * @Date: 14:36 2020/02/10
 */
@Component
@Configuration
public class WebAppConfig extends WebMvcConfigurationSupport {
    @Autowired
    private PermissionInterceptor permissionInterceptor;
    @Autowired
    private LogInterceptor logInterceptor;

    @Override
    protected void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new EnumConvertFactory());
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //权限校验拦截器
        registry.addInterceptor(permissionInterceptor)
                //排除拦截规则
                .excludePathPatterns("/sys/login","/sys/logout",
                        "/webjars/**","/v2/**", "/swagger-ui.html", "/doc.html","/swagger-resources/**")
//                .excludePathPatterns("/**")
        //拦截规则
        ;
        //日志记录拦截器
        registry.addInterceptor(logInterceptor)
                .excludePathPatterns("/webjars/**","/v2/**", "/swagger-ui.html", "/doc.html","/swagger-resources/**");
        super.addInterceptors(registry);
    }

    /**
     * 跨域处理
     */
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.setMaxAge(18000L);
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
